#Region " Imports "

Imports System
Imports System.Data
Imports BlazeApps.Library.Blog
Imports System.Globalization

#End Region

Partial Class Usercontrols_Blog_BlogList
    Inherits UserControlBase

#Region " Enums, Memebers and Properties "

    Private DataPageLocal As New PagedDataSource

    Public Property sortCriteria() As String
        Get
            Return CStr(ViewState("sortCriteria"))
        End Get

        Set(ByVal Value As String)
            ViewState("sortCriteria") = Value
        End Set
    End Property

    Public Property sortDir() As String
        Get
            Return CStr(ViewState("sortDir"))
        End Get

        Set(ByVal Value As String)
            ViewState("sortDir") = Value
        End Set
    End Property

    Private Property SelectedMonth() As Integer
        Get
            Return GetIntegerFromVS("SelectedMonth")
        End Get
        Set(ByVal value As Integer)
            ViewState.Add("SelectedMonth", value)
        End Set
    End Property

    Private Property SelectedYear() As Integer
        Get
            Return GetIntegerFromVS("SelectedYear")
        End Get
        Set(ByVal value As Integer)
            ViewState.Add("SelectedYear", value)
        End Set
    End Property

    Public Property MyBlogs() As Boolean
        Get
            Return GetBooleanFromVS("MyBlogs")
        End Get
        Set(ByVal value As Boolean)
            ViewState.Add("MyBlogs", value)
        End Set
    End Property

    Public Property BlogsByUser() As Boolean
        Get
            Return GetBooleanFromVS("BlogsByUser")
        End Get
        Set(ByVal value As Boolean)
            ViewState.Add("BlogsByUser", value)
        End Set
    End Property

    Public Property IsLoadedAsOption() As Boolean
        Get
            Return GetBooleanFromVS("IsLoadedAsOption")
        End Get
        Set(ByVal value As Boolean)
            ViewState.Add("IsLoadedAsOption", value)
        End Set
    End Property

#End Region

#Region " Page Events "

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not IsLoadedAsOption Then
            SetPageTitle(Resources.Resource.BlogList)
        End If

        If MyBlogs = True Then
            HideReports()
        End If

        If Me.Page.IsPostBack = False Then
            'Set Default Sort Order and Direction
            Me.sortCriteria = "createdate"
            Me.sortDir = "desc"

            LoadPage()
        End If

        ConfigBaseNavCtrls()

        If Me.Page.IsPostBack = False Then
            'Load ViewState Values
            SelectedMonth = DateTime.Now.Month
            SelectedYear = DateTime.Now.Year

            BuildMonthList()
            BindDataItems()
        End If

        LoadSettings()

        SetPanelState(Me.uxAddBlogPanel, IsAllowed(), IsAllowed())

    End Sub

#End Region

#Region " Save Data "


#End Region

#Region " Load Data "

    Private Sub LoadPage()
        LoadPageSize(Me.uxPageSizeDropDownList)
    End Sub

    Private Sub LoadSettings()
        MostViewedPanel.Visible = DisplayMostViewedBlogs
        MostCommentsPanel.Visible = DisplayMostCommentsBlogs
        HighestRankedPanel.Visible = DisplayHighestRankedBlogs

        MostViewedPanel.Enabled = DisplayMostViewedBlogs
        MostCommentsPanel.Enabled = DisplayMostCommentsBlogs
        HighestRankedPanel.Enabled = DisplayHighestRankedBlogs
    End Sub

    Public Overloads Overrides Sub BindDataItems()
        Dim List As New BlogList
        Dim DT As New DataTable
        Dim DV As New DataView

        uxBlogCalendar.SelectedDates.Clear()

        DT = GetData()

        DV.Table = DT

        DV.Sort = Me.sortCriteria & " " & Me.sortDir

        If Not (Me.uxSearchTextBox.Text = String.Empty) Then
            DV.RowFilter = String.Format("title like '%{0}%' or body like '%{0}%'", Replace(Me.uxSearchTextBox.Text, "'", "''"))
        End If

        Me.RecordCount = DV.Count

        Me.DataPage.DataSource = DV
        Me.DataPage.AllowPaging = True
        Me.DataPage.PageSize = CType(Me.uxPageSizeDropDownList.SelectedValue.ToString, Integer)
        Me.DataPage.CurrentPageIndex = Me.PageNumber

        CreatePagingLinks()

        With Me.uxBlogRepeater
            .DataSource = Me.DataPage
            .DataBind()
        End With

        uxBlogCalendar.TodaysDate = New Date(SelectedYear, SelectedMonth, 1)

    End Sub

    Private Function GetData() As DataTable

        Dim List As New BlogList
        Dim DT As New DataTable

        If Not (Me.uxSearchTextBox.Text = String.Empty) Then
            If GetBooleanFromQueryString("UsersBlog") OrElse BlogsByUser Then
                DT = List.SearchBlogs(Membership.GetUser(GetStringFromQueryString("userid")).ProviderUserKey)
            Else
                DT = List.SearchBlogs()
            End If
        Else
            If GetBooleanFromQueryString("MyBlogs") OrElse MyBlogs = True Then
                If IsUserAuthenticated Then
                    DT = List.GetBlogs(CurrentUserID, SelectedMonth, SelectedYear, BlogList.BlogType.MyBlogs)
                    Me.uxTitleLiteral.Text = String.Format("{0} {1}", CurrentUser, Resources.Resource.Blogs.ToString().Trim())
                Else
                    DT = List.GetBlogs(SelectedMonth, SelectedYear)
                End If
            ElseIf GetBooleanFromQueryString("UsersBlog") OrElse BlogsByUser Then
                DT = List.GetBlogs(Membership.GetUser(GetStringFromQueryString("userid")).ProviderUserKey, SelectedMonth, SelectedYear, BlogList.BlogType.BlogsByUser)
                Me.uxTitleLiteral.Text = String.Format("{0}'s {1}", GetStringFromQueryString("userid"), Resources.Resource.Blogs.ToString().Trim())
            Else
                DT = List.GetBlogs(SelectedMonth, SelectedYear)
            End If
        End If

        DT.TableName = "Results"

        Return DT

    End Function

    Private Sub BuildMonthList()
        Dim List As New BlogList
        Dim DT As New DataTable

        If GetBooleanFromQueryString("UsersBlog") OrElse BlogsByUser Then
            DT = List.GetBlogPeriods(Membership.GetUser(GetStringFromQueryString("userid")).ProviderUserKey)
        Else
            DT = List.GetBlogPeriods()

        End If

        For Each row As DataRow In DT.Rows
            Me.uxMonthList.Items.Add(New ListItem(String.Format("{0}, {1}({2})", DateTimeFormatInfo.CurrentInfo.GetMonthName(CType(row("blogmonth"), Integer)).ToString, CType(row("blogyear"), Integer), CType(row("blogcount"), Integer)), String.Format("{0}|{1}", CType(row("blogmonth"), Integer), CType(row("blogyear"), Integer))))
        Next

    End Sub

    Private Sub HideReports()
        uxMostViewed.Visible = False
        uxMostComments.Visible = False
        uxHighestRanked.Visible = False
    End Sub

#End Region

#Region " Form Controls Events "

    Protected Sub uxAddBlogButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxAddBlogButton.Click
        Response.Redirect("~/blog.aspx?pid=blg_addblog")
    End Sub

    Protected Sub LoadBlogs(ByVal sender As Object, ByVal e As BulletedListEventArgs)
        Dim Values As String()

        Me.uxSearchTextBox.Text = String.Empty

        Values = Split(uxMonthList.Items(e.Index).Value.ToString, "|")

        SelectedMonth = Values(0)
        SelectedYear = Values(1)

        BindDataItems()
    End Sub

    Protected Sub uxSearchButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxSearchButton.Click
        BindDataItems()
    End Sub

    Protected Sub uxBlogRepeater_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles uxBlogRepeater.ItemDataBound
        Dim HL As HyperLink = CType(e.Item.FindControl("uxEditBlogHyperlink"), HyperLink)

        If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
            Dim dayDate As Date = e.Item.DataItem("createdate")
            uxBlogCalendar.SelectedDates.Add(dayDate)

            If IsUserAuthenticated Then
                If IsAllowedEdit(e.Item.DataItem("userid").ToString) Then
                    HL.Visible = True
                End If
            End If

        End If

    End Sub

#End Region

#Region " Helpers and Methods "

    Private Sub ConfigBaseNavCtrls()

        Me.PagingTopPanel = Me.uxPagingTopPanel
        Me.PagingBottomPanel = Me.uxPagingBottomPanel

        Me.RepeaterTop = Me.uxPagesTopRepeater
        Me.RepeaterBottom = Me.uxPagesBottomRepeater

        Me.NextTopLinkButton = Me.uxTopNextLinkButton
        Me.PreviousTopLinkButton = Me.uxTopPrevLinkButton
        Me.NextBottomLinkButton = Me.uxBottomNextLinkButton
        Me.PreviousBottomLinkButton = Me.uxBottomPrevLinkButton

        Me.DataPage = DataPageLocal
        Me.PageSize = CType(Me.uxPageSizeDropDownList.SelectedValue.ToString, Integer)
        Me.PagesToDisplay = 10

        Me.ItemsPerPageDropDown = Me.uxPageSizeDropDownList
        Me.ItemsPerPageLabel = Me.uxItemsPerPageLabel
        Me.PagerInfoLabel = Me.uxPagerInfoLabel

        AddHandler Me.RepeaterTop.ItemCommand, AddressOf PagingRepeater_ItemCommand
        AddHandler Me.RepeaterBottom.ItemCommand, AddressOf PagingRepeater_ItemCommand

    End Sub

    Private Function IsAllowed() As Boolean
        If GetBooleanFromQueryString("UsersBlog") OrElse BlogsByUser Then
            Return False
        Else
            Return (((MyBlogs OrElse IsUserAuthenticated) And EnableUserBlogs) OrElse IsBlogModerator())
        End If
    End Function

    Private Function IsAllowedEdit(ByVal UserID As String) As Boolean
        Return (CurrentUserID = ConvertToGuid(UserID) OrElse IsBlogModerator())
    End Function

    Private Function IsAllowedDelete(ByVal UserID As String) As Boolean
        Return (CurrentUserID = ConvertToGuid(UserID) OrElse IsBlogModerator())
    End Function

#End Region

End Class
